package test.ws;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import test.PerformanceAnalyze;

public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    PerformanceAnalyze performanceAnalyze = new PerformanceAnalyze();

    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf m = (ByteBuf) msg; // (1)
        try {
            while (m.isReadable() && m.readerIndex()+8 <= m.readableBytes()) {
                ByteBuf time = ctx.alloc().buffer(8); // (2)
                time.writeLong(m.readLong());
                ctx.write(time); // (3)
//                time.clear();

                performanceAnalyze.meter();
            }
        } finally {
            ctx.flush();
            m.release();
        }

    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
